# GPL3 or any later version

import os
import gi
import threading
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib


from modules import wallet
from modules import ui

def refresh_wallets(box, wallets, win):

    for i in box.get_children():
        i.destroy()

    wallets_box = Gtk.VBox()
    for i in wallets:
        wallet_button = Gtk.Button()
        button_box = Gtk.HBox()
        wallet_button.add(button_box)
        button_box.pack_start(ui.icon(win, "x-office-presentation"), 0,0,0)
        button_box.pack_start(Gtk.Label(i), 1,1,5)
        wallet_button.set_relief(Gtk.ReliefStyle.NONE)

        def choose(w, win, name):
            win.wallet = name
            win.destroy()
            
        wallet_button.connect("clicked", choose, win, i)
        
        box.pack_start(wallet_button, 0,0,0)
   
    box.show_all()
        
def select_wallet():

    win = Gtk.Window()                    
    win.connect("destroy", Gtk.main_quit) 
    win.set_title("J.Y.Transactions")         
    win.set_default_icon_from_file("icon_small.png") 
    win.set_size_request(300, 300)

    box = Gtk.VBox()
    win.add(box)

    pannel = Gtk.HeaderBar()
    pannel.set_show_close_button(True)
    win.set_titlebar(pannel) 

    # Let's get list of wallets
    wallets = wallet.get_list()


    # Adding menu
    add_menu = Gtk.Popover()
    add_box = Gtk.VBox()
    add_menu.add(add_box)

    add_name = Gtk.Entry()
    add_box.pack_start(add_name, 0,0,0)
    add_do = Gtk.Button("Add Wallet")
    add_do.set_relief(Gtk.ReliefStyle.NONE)
    add_box.pack_start(add_do, 0,0,0)

    def add_wallet_function(w):
        add_menu.hide()
        folder = wallet.save_folder()+"wallets/"+add_name.get_text()
        try:
            os.makedirs(folder)
        except:
            pass
        wallets = wallet.get_list()
        refresh_wallets(box, wallets, win)        
        
    add_do.connect("clicked", add_wallet_function)
    add_name.connect("activate", add_wallet_function)
    
    add_box.show_all()

    # Adding button
    add_button = Gtk.MenuButton(popover=add_menu)
    add_button.set_relief(Gtk.ReliefStyle.NONE)
    add_button.add(ui.icon(win, "list-add"))
    add_button.set_tooltip_text("Add Wallet")
    pannel.pack_start(add_button)


    pannel.pack_start(Gtk.Label("Select Wallet"))

    if not wallets:
        box.pack_start(Gtk.Label("You have no wallets yet."), 1,1,1)
    else:
        refresh_wallets(box, wallets, win)
    
    win.wallet = False
    win.show_all()
    Gtk.main()
    
    return win.wallet
